home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2007 September / PCWSEP07.iso / Software / Linux / Linux Mint 3.0 Light / LinuxMint-3.0-Light.iso / casper / filesystem.squashfs / usr / lib / hplip / unload < prev   
Encoding:
Text File  |  2007-04-04  |  26.4 KB  |  847 lines

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # (c) Copyright 2003-2007 Hewlett-Packard Development Company, L.P.
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
  19. #
  20. # Author: Don Welch
  21. #
  22.  
  23. __version__ = '2.2'
  24. __title__ = 'Photo Card Access Utility'
  25. __doc__ = "Access inserted photo cards on supported HPLIP printers. This provides an alternative for older devices that do not support USB mass storage or for access to photo cards over a network."
  26.  
  27. # Std Lib
  28. import sys
  29. import os, os.path
  30. import getopt
  31. import re
  32. import cmd
  33. import readline
  34. import time
  35. import fnmatch
  36. import string
  37.  
  38. # Local
  39. from base.g import *
  40. from base import device, service, utils #, exif
  41. from prnt import cups
  42. from pcard import photocard
  43.  
  44. log.set_module('hp-unload')
  45.  
  46.  
  47. USAGE = [(__doc__, "", "name", True),
  48.          ("Usage: hp-unload [PRINTER|DEVICE-URI] [MODE] [OPTIONS]", "", "summary", True),
  49.          utils.USAGE_ARGS,
  50.          utils.USAGE_DEVICE,
  51.          utils.USAGE_PRINTER,
  52.          utils.USAGE_SPACE,
  53.          ("[MODE]", "", "header", False),
  54.          ("Enter interactive mode (ftp-like interface):", "-i or --interactive", "option", False),
  55.          ("Enter graphical UI mode:", "-u or --gui (Default)", "option", False),
  56.          ("Run in non-interactive mode (batch mode):", "-n or --non-interactive", "option", False),
  57.          # TODO: File glob(s)
  58.          utils.USAGE_SPACE,
  59.          utils.USAGE_OPTIONS,
  60.          ("Output directory:", "-o<dir> or --output=<dir> (Defaults to current directory)(Only used for non-GUI modes)", "option", False),
  61.          utils.USAGE_BUS1, utils.USAGE_BUS2,
  62.          utils.USAGE_LOGGING1, utils.USAGE_LOGGING2, utils.USAGE_LOGGING3,
  63.          utils.USAGE_HELP,
  64.          utils.USAGE_SPACE,
  65.          utils.USAGE_NOTES,
  66.          utils.USAGE_STD_NOTES1, utils.USAGE_STD_NOTES2, 
  67.          ("3. Use 'help' command at the pcard:> prompt for command help (Interactive mode (-i) only).", "", "note", True),
  68.          ]
  69.  
  70. def usage(typ='text'):
  71.     if typ == 'text':
  72.         utils.log_title(__title__, __version__)
  73.  
  74.     utils.format_text(USAGE, typ, __title__, 'hp-unload', __version__)
  75.     sys.exit(0)
  76.  
  77.  
  78. ## Console class (from ASPN Python Cookbook)
  79. ## Author:   James Thiele
  80. ## Date:     27 April 2004
  81. ## Version:  1.0
  82. ## Location: http://www.eskimo.com/~jet/python/examples/cmd/
  83. ## Copyright (c) 2004, James Thiele
  84.  
  85. class Console(cmd.Cmd):
  86.  
  87.     def __init__(self, pc):
  88.         cmd.Cmd.__init__(self)
  89.         self.intro  = "Type 'help' for a list of commands. Type 'exit' to quit."
  90.         self.pc = pc
  91.         disk_info = self.pc.info()
  92.         pc.write_protect = disk_info[8]
  93.         if pc.write_protect:
  94.             log.warning("Photo card is write protected.")
  95.         self.prompt = utils.bold("pcard: %s > " % self.pc.pwd())
  96.  
  97.     ## Command definitions ##
  98.     def do_hist(self, args):
  99.         """Print a list of commands that have been entered"""
  100.         print self._hist
  101.  
  102.     def do_exit(self, args):
  103.         """Exits from the console"""
  104.         return -1
  105.  
  106.     def do_quit(self, args):
  107.         """Exits from the console"""
  108.         return -1
  109.  
  110.     ## Command definitions to support Cmd object functionality ##
  111.     def do_EOF(self, args):
  112.         """Exit on system end of file character"""
  113.         return self.do_exit(args)
  114.  
  115.     def do_help(self, args):
  116.         """Get help on commands
  117.            'help' or '?' with no arguments prints a list of commands for which help is available
  118.            'help <command>' or '? <command>' gives help on <command>
  119.         """
  120.         ## The only reason to define this method is for the help text in the doc string
  121.         cmd.Cmd.do_help(self, args)
  122.  
  123.     ## Override methods in Cmd object ##
  124.     def preloop(self):
  125.         """Initialization before prompting user for commands.
  126.            Despite the claims in the Cmd documentaion, Cmd.preloop() is not a stub.
  127.         """
  128.         cmd.Cmd.preloop(self)   ## sets up command completion
  129.         self._hist    = []      ## No history yet
  130.         self._locals  = {}      ## Initialize execution namespace for user
  131.         self._globals = {}
  132.  
  133.     def postloop(self):
  134.         """Take care of any unfinished business.
  135.            Despite the claims in the Cmd documentaion, Cmd.postloop() is not a stub.
  136.         """
  137.         cmd.Cmd.postloop(self)   ## Clean up command completion
  138.         print "Exiting..."
  139.  
  140.     def precmd(self, line):
  141.         """ This method is called after the line has been input but before
  142.             it has been interpreted. If you want to modifdy the input line
  143.             before execution (for example, variable substitution) do it here.
  144.         """
  145.         self._hist += [line.strip()]
  146.         return line
  147.  
  148.     def postcmd(self, stop, line):
  149.         """If you want to stop the console, return something that evaluates to true.
  150.            If you want to do some post command processing, do it here.
  151.         """
  152.         return stop
  153.  
  154.     def emptyline(self):
  155.         """Do nothing on empty input line"""
  156.         pass
  157.  
  158.     def default(self, line):
  159.         print utils.bold("ERROR: Unrecognized command. Use 'help' to list commands.")
  160.  
  161.     def do_ldir(self, args):
  162.         """ List local directory contents."""
  163.         os.system('ls -l')
  164.  
  165.     def do_lls(self, args):
  166.         """ List local directory contents."""
  167.         os.system('ls -l')
  168.  
  169.     def do_dir(self, args):
  170.         """Synonym for the ls command."""
  171.         return self.do_ls(args)
  172.  
  173.     def do_ls(self, args):
  174.         """List photo card directory contents."""
  175.         args = args.strip().lower()
  176.         files = self.pc.ls(True, args)
  177.  
  178.         total_size = 0
  179.         formatter = utils.TextFormatter(
  180.                 (
  181.                     {'width': 14, 'margin' : 2},
  182.                     {'width': 12, 'margin' : 2, 'alignment' : utils.TextFormatter.RIGHT},
  183.                     {'width': 30, 'margin' : 2},
  184.                 )
  185.             )
  186.  
  187.         print
  188.         print utils.bold(formatter.compose(("Name", "Size", "Type")))
  189.  
  190.         num_files = 0
  191.         for d in self.pc.current_directories():
  192.             if d[0] in ('.', '..'):
  193.                 print formatter.compose((d[0], "", "directory"))
  194.             else:
  195.                 print formatter.compose((d[0] + "/", "", "directory"))
  196.  
  197.         for f in self.pc.current_files():
  198.             print formatter.compose((f[0], utils.format_bytes(f[2]), self.pc.classify_file(f[0])))
  199.             num_files += 1
  200.             total_size += f[2]
  201.  
  202.         print utils.bold("% d files, %s" % (num_files, utils.format_bytes(total_size, True)))
  203.  
  204.  
  205.     def do_df(self, args):
  206.         """Display free space on photo card.
  207.         Options:
  208.         -h\tDisplay in human readable format
  209.         """
  210.         freespace = self.pc.df()
  211.  
  212.         if args.strip().lower() == '-h':
  213.             fs = utils.format_bytes(freespace)
  214.         else:
  215.             fs = utils.commafy(freespace)
  216.  
  217.         print "Freespace = %s Bytes" % fs
  218.  
  219.  
  220.     def do_cp(self, args, remove_after_copy=False):
  221.         """Copy files from photo card to current local directory.
  222.         Usage:
  223.         \tcp FILENAME(S)|GLOB PATTERN(S)
  224.         Example:
  225.         \tCopy all JPEG and GIF files and a file named thumbs.db from photo card to local directory:
  226.         \tcp *.jpg *.gif thumbs.db
  227.         """
  228.         args = args.strip().lower()
  229.  
  230.         matched_files = self.pc.match_files(args)
  231.  
  232.         if len(matched_files) == 0:
  233.             print "ERROR: File(s) not found."
  234.         else:
  235.             total, delta = self.pc.cp_multiple(matched_files, remove_after_copy, self.cp_status_callback, self.rm_status_callback)
  236.  
  237.             print utils.bold("\n%s transfered in %d sec (%d KB/sec)" % (utils.format_bytes(total), delta, (total/1024)/(delta)))
  238.  
  239.     def do_unload(self, args):
  240.         """Unload all image files from photocard to current local directory.
  241.         Note:
  242.         \tSubdirectories on photo card are not preserved
  243.         Options:
  244.         -x\tDon't remove files after copy
  245.         -p\tPrint unload list but do not copy or remove files"""
  246.         args = args.lower().strip().split()
  247.         dont_remove = False
  248.         if '-x' in args:
  249.             if self.pc.write_protect:
  250.                 log.error("Photo card is write protected. -x not allowed.")
  251.                 return
  252.             else:
  253.                 dont_remove = True
  254.  
  255.  
  256.         unload_list = self.pc.get_unload_list()
  257.         print
  258.  
  259.         if len(unload_list) > 0:
  260.             if '-p' in args:
  261.  
  262.                 max_len = 0
  263.                 for u in unload_list:
  264.                     max_len = max(max_len, len(u[0]))
  265.  
  266.                 formatter = utils.TextFormatter(
  267.                         (
  268.                             {'width': max_len+2, 'margin' : 2},
  269.                             {'width': 12, 'margin' : 2, 'alignment' : utils.TextFormatter.RIGHT},
  270.                             {'width': 12, 'margin' : 2},
  271.                         )
  272.                     )
  273.  
  274.                 print
  275.                 print utils.bold(formatter.compose(("Name", "Size", "Type")))
  276.  
  277.                 total = 0
  278.                 for u in unload_list:
  279.                      print formatter.compose(('%s' % u[0], utils.format_bytes(u[1]), '%s/%s' % (u[2], u[3])))
  280.                      total += u[1]
  281.  
  282.  
  283.                 print utils.bold("Found %d files to unload, %s" % (len(unload_list), utils.format_bytes(total, True)))
  284.             else:
  285.                 print utils.bold("Unloading %d files..." % len(unload_list))
  286.                 total, delta, was_cancelled = self.pc.unload(unload_list, self.cp_status_callback, self.rm_status_callback, dont_remove)
  287.                 print utils.bold("\n%s unloaded in %d sec (%d KB/sec)" % (utils.format_bytes(total), delta, (total/1024)/delta))
  288.  
  289.         else:
  290.             print "No image, audio, or video files found."
  291.  
  292.  
  293.     def cp_status_callback(self, src, trg, size):
  294.         if size == 1:
  295.             print
  296.             print utils.bold("Copying %s..." % src)
  297.         else:
  298.             print "\nCopied %s to %s (%s)..." % (src, trg, utils.format_bytes(size))
  299.  
  300.     def rm_status_callback(self, src):
  301.         print "Removing %s..." % src
  302.  
  303.  
  304.  
  305.     def do_rm(self, args):
  306.         """Remove files from photo card."""
  307.         if self.pc.write_protect:
  308.             log.error("Photo card is write protected. rm not allowed.")
  309.             return
  310.  
  311.         args = args.strip().lower()
  312.  
  313.         matched_files = self.pc.match_files(args)
  314.  
  315.         if len(matched_files) == 0:
  316.             print "ERROR: File(s) not found."
  317.         else:
  318.             for f in matched_files:
  319.                 self.pc.rm(f, False)
  320.  
  321.         self.pc.ls()
  322.  
  323.     def do_mv(self, args):
  324.         """Move files off photocard"""
  325.         if self.pc.write_protect:
  326.             log.error("Photo card is write protected. mv not allowed.")
  327.             return
  328.         self.do_cp(args, True)
  329.  
  330.     def do_lpwd(self, args):
  331.         """Print name of local current/working directory."""
  332.         print os.getcwd()
  333.  
  334.     def do_lcd(self, args):
  335.         """Change current local working directory."""
  336.         try:
  337.             os.chdir(args.strip())
  338.         except OSError:
  339.             print utils.bold("ERROR: Directory not found.")
  340.         print os.getcwd()
  341.  
  342.     def do_pwd(self, args):
  343.         """Print name of photo card current/working directory
  344.         Usage:
  345.         \t>pwd"""
  346.         print self.pc.pwd()
  347.  
  348.     def do_cd(self, args):
  349.         """Change current working directory on photo card.
  350.         Note:
  351.         \tYou may only specify one directory level at a time.
  352.         Usage:
  353.         \tcd <directory>
  354.         """
  355.         args = args.lower().strip()
  356.  
  357.         if args == '..':
  358.             if self.pc.pwd() != '/':
  359.                 self.pc.cdup()
  360.  
  361.         elif args == '.':
  362.             pass
  363.  
  364.         elif args == '/':
  365.             self.pc.cd('/')
  366.  
  367.         else:
  368.             matched_dirs = self.pc.match_dirs(args)
  369.  
  370.             if len(matched_dirs) == 0:
  371.                 print "Directory not found"
  372.  
  373.             elif len(matched_dirs) > 1:
  374.                 print "Pattern matches more than one directory"
  375.  
  376.             else:
  377.                 self.pc.cd(matched_dirs[0])
  378.  
  379.         self.prompt = utils.bold("pcard: %s > " % self.pc.pwd())
  380.  
  381.     def do_cdup(self, args):
  382.         """Change to parent directory."""
  383.         self.do_cd('..')
  384.  
  385.     #def complete_cd( self, text, line, begidx, endidx ):
  386.     #    print text, line, begidx, endidx
  387.     #    #return "XXX"
  388.  
  389.     def do_cache(self, args):
  390.         """Display current cache entries, or turn cache on/off.
  391.         Usage:
  392.         \tDisplay: cache
  393.         \tTurn on: cache on
  394.         \tTurn off: cache off
  395.         """
  396.         args = args.strip().lower()
  397.  
  398.         if args == 'on':
  399.             self.pc.cache_control(True)
  400.  
  401.         elif args == 'off':
  402.             self.pc.cache_control(False)
  403.  
  404.         else:
  405.             if self.pc.cache_state():
  406.                 cache_info = self.pc.cache_info()
  407.  
  408.                 t = cache_info.keys()
  409.                 t.sort()
  410.                 print
  411.                 for s in t:
  412.                     print "sector %d (%d hits)" % (s, cache_info[s])
  413.  
  414.                 print utils.bold("Total cache usage: %s (%s maximum)" % (utils.format_bytes(len(t)*512), utils.format_bytes(photocard.MAX_CACHE * 512)))
  415.                 print utils.bold("Total cache sectors: %s of %s" % (utils.commafy(len(t)), utils.commafy(photocard.MAX_CACHE)))
  416.             else:
  417.                 print "Cache is off."
  418.  
  419.     def do_sector(self, args):
  420.         """Display sector data.
  421.         Usage:
  422.         \tsector <sector num>
  423.         """
  424.         args = args.strip().lower()
  425.         cached = False
  426.         try:
  427.             sector = int(args)
  428.         except ValueError:
  429.             print "Sector must be specified as a number"
  430.             return
  431.  
  432.         if self.pc.cache_check(sector) > 0:
  433.             print "Cached sector"
  434.  
  435.         print repr(self.pc.sector(sector))
  436.  
  437.  
  438.     def do_tree(self, args):
  439.         """Display photo card directory tree."""
  440.         tree = self.pc.tree()
  441.         print
  442.         self.print_tree(tree)
  443.  
  444.     def print_tree(self, tree, level=0):
  445.         for d in tree:
  446.             if type(tree[d]) == type({}):
  447.                 print ''.join([' '*level*4, d, '/'])
  448.                 self.print_tree(tree[d], level+1)
  449.  
  450.  
  451.     def do_reset(self, args):
  452.         """Reset the cache."""
  453.         self.pc.cache_reset()
  454.  
  455.  
  456.     def do_card(self, args):
  457.         """Print info about photocard."""
  458.         print
  459.         print "Device URI = %s" % self.pc.device.device_uri
  460.         print "Model = %s" % self.pc.device.model_ui
  461.         print "Working dir = %s" % self.pc.pwd()
  462.         disk_info = self.pc.info()
  463.         print "OEM ID = %s" % disk_info[0]
  464.         print "Bytes/sector = %d" % disk_info[1]
  465.         print "Sectors/cluster = %d" % disk_info[2]
  466.         print "Reserved sectors = %d" % disk_info[3]
  467.         print "Root entries = %d" % disk_info[4]
  468.         print "Sectors/FAT = %d" % disk_info[5]
  469.         print "Volume label = %s" % disk_info[6]
  470.         print "System ID = %s" % disk_info[7]
  471.         print "Write protected = %d" % disk_info[8]
  472.         print "Cached sectors = %s" % utils.commafy(len(self.pc.cache_info()))
  473.  
  474.  
  475.     def do_display(self, args):
  476.         """Display an image with ImageMagick.
  477.         Usage:
  478.         \tdisplay <filename>"""
  479.         args = args.strip().lower()
  480.         matched_files = self.pc.match_files(args)
  481.  
  482.         if len(matched_files) == 1:
  483.  
  484.             typ = self.pc.classify_file(args).split('/')[0]
  485.  
  486.             if typ == 'image':
  487.                 fd, temp_name = utils.make_temp_file()
  488.                 self.pc.cp(args, temp_name)
  489.                 os.system('display %s' % temp_name)
  490.                 os.remove(temp_name)
  491.  
  492.             else:
  493.                 print "File is not an image."
  494.  
  495.         elif len(matched_files) == 0:
  496.             print "File not found."
  497.  
  498.         else:
  499.             print "Only one file at a time may be specified for display."
  500.  
  501.     def do_show(self, args):
  502.         """Synonym for the display command."""
  503.         self.do_display(args)
  504.  
  505.     def do_thumbnail(self, args):
  506.         """Display an embedded thumbnail image with ImageMagick.
  507.         Note:
  508.         \tOnly works with JPEG/JFIF images with embedded JPEG/TIFF thumbnails
  509.         Usage:
  510.         \tthumbnail <filename>"""
  511.         args = args.strip().lower()
  512.         matched_files = self.pc.match_files(args)
  513.  
  514.         if len(matched_files) == 1:
  515.             typ, subtyp = self.pc.classify_file(args).split('/')
  516.  
  517.             if typ == 'image' and subtyp in ('jpeg', 'tiff'):
  518.                 exif_info = self.pc.get_exif(args)
  519.  
  520.                 dir_name, file_name=os.path.split(args)
  521.                 photo_name, photo_ext=os.path.splitext(args)
  522.  
  523.                 if 'JPEGThumbnail' in exif_info:
  524.                     temp_file_fd, temp_file_name = utils.make_temp_file()
  525.                     open(temp_file_name, 'wb').write(exif_info['JPEGThumbnail'])
  526.                     os.system('display %s' % temp_file_name)
  527.                     os.remove(temp_file_name)
  528.  
  529.                 elif 'TIFFThumbnail' in exif_info:
  530.                     temp_file_fd, temp_file_name = utils.make_temp_file()
  531.                     open(temp_file_name, 'wb').write(exif_info['TIFFThumbnail'])
  532.                     os.system('display %s' % temp_file_name)
  533.                     os.remove(temp_file_name)
  534.  
  535.                 else:
  536.                     print "No thumbnail found."
  537.  
  538.             else:
  539.                 print "Incorrect file type for thumbnail."
  540.  
  541.         elif len(matched_files) == 0:
  542.             print "File not found."
  543.         else:
  544.             print "Only one file at a time may be specified for thumbnail display."
  545.  
  546.     def do_thumb(self, args):
  547.         """Synonym for the thumbnail command."""
  548.         self.do_thumbnail(args)
  549.  
  550.     def do_exif(self, args):
  551.         """Display EXIF info for file.
  552.         Usage:
  553.         \texif <filename>"""
  554.         args = args.strip().lower()
  555.         matched_files = self.pc.match_files(args)
  556.  
  557.         if len(matched_files) == 1:
  558.             typ, subtyp = self.pc.classify_file(args).split('/')
  559.             #print "'%s' '%s'" % (typ, subtyp)
  560.  
  561.             if typ == 'image' and subtyp in ('jpeg', 'tiff'):
  562.                 exif_info = self.pc.get_exif(args)
  563.  
  564.                 formatter = utils.TextFormatter(
  565.                         (
  566.                             {'width': 40, 'margin' : 2},
  567.                             {'width': 40, 'margin' : 2},
  568.                         )
  569.                     )
  570.  
  571.                 print
  572.                 print utils.bold(formatter.compose(("Tag", "Value")))
  573.  
  574.                 ee = exif_info.keys()
  575.                 ee.sort()
  576.                 for e in ee:
  577.                     if e not in ('JPEGThumbnail', 'TIFFThumbnail', 'Filename'):
  578.                         #if e != 'EXIF MakerNote':
  579.                         print formatter.compose((e, '%s' % exif_info[e]))
  580.                         #else:
  581.                         #    print formatter.compose( ( e, ''.join( [ chr(x) for x in exif_info[e].values if chr(x) in string.printable ] ) ) )
  582.             else:
  583.                 print "Incorrect file type for thumbnail."
  584.  
  585.         elif len(matched_files) == 0:
  586.             print "File not found."
  587.         else:
  588.             print "Only one file at a time may be specified for thumbnail display."
  589.  
  590.     def do_info(self, args):
  591.         """Synonym for the exif command."""
  592.         self.do_exif(args)
  593.  
  594.     def do_about(self, args):
  595.         utils.log_title(__title__, __version__)
  596.  
  597.  
  598. def status_callback(src, trg, size):
  599.     if size == 1:
  600.         print
  601.         print utils.bold("Copying %s..." % src)
  602.     else:
  603.         print "\nCopied %s to %s (%s)..." % (src, trg, utils.format_bytes(size))
  604.  
  605.  
  606.  
  607. try:
  608.     opts, args = getopt.getopt(sys.argv[1:], 'p:d:hb:l:giuno:',
  609.                                ['printer=', 'device=', 'help', 'help-rest', 'help-man',
  610.                                 'bus=', 'logging=', 'interactive', 'gui', 'non-interactive',
  611.                                 'output=', 'help-desc'])
  612. except getopt.GetoptError:
  613.     usage()
  614.  
  615. printer_name = None
  616. device_uri = None
  617. bus = device.DEFAULT_PROBE_BUS
  618. log_level = logger.DEFAULT_LOG_LEVEL
  619. mode = GUI_MODE
  620. mode_specified = False
  621. output_dir = os.getcwd()
  622.  
  623. if os.getenv("HPLIP_DEBUG"):
  624.     log.set_level('debug')
  625.  
  626. for o, a in opts:
  627.     if o in ('-h', '--help'):
  628.         usage()
  629.  
  630.     elif o == '--help-rest':
  631.         usage('rest')
  632.  
  633.     elif o == '--help-man':
  634.         usage('man')
  635.  
  636.     elif o == '--help-desc':
  637.         print __doc__,
  638.         sys.exit(0)
  639.  
  640.     elif o in ('-p', '--printer'):
  641.         printer_name = a
  642.  
  643.     elif o in ('-d', '--device'):
  644.         device_uri = a
  645.  
  646.     elif o in ('-b', '--bus'):
  647.         bus = a.lower().strip()
  648.         if not device.validateBusList(bus):
  649.             usage()
  650.  
  651.     elif o in ('-l', '--logging'):
  652.         log_level = a.lower().strip()
  653.         if not log.set_level(log_level):
  654.             usage()
  655.  
  656.     elif o == '-g':
  657.         log.set_level('debug')
  658.  
  659.     elif o in ('-i', '--interactive'):
  660.         if mode_specified:
  661.             log.error("You may only specify a single mode as a parameter (-i, -n or -u).")
  662.             sys.exit(1)
  663.  
  664.         mode = INTERACTIVE_MODE
  665.         mode_specified = True
  666.  
  667.     elif o in ('-u', '--gui'):
  668.         if mode_specified:
  669.             log.error("You may only specify a single mode as a parameter (-i, -n or -u).")
  670.             sys.exit(1)
  671.  
  672.         mode = GUI_MODE
  673.         mode_specified = True
  674.  
  675.     elif o in ('-n', '--non-interactive'):
  676.         if mode_specified:
  677.             log.error("You may only specify a single mode as a parameter (-i, -n or -u).")
  678.             sys.exit(1)
  679.  
  680.         mode = NON_INTERACTIVE_MODE
  681.         mode_specified = True
  682.  
  683.     elif o in ('-o', '--output'):
  684.         output_dir = a
  685.  
  686.  
  687. utils.log_title(__title__, __version__)
  688.  
  689. # Security: Do *not* create files that other users can muck around with
  690. os.umask (0077)
  691.  
  692. if mode == GUI_MODE:
  693.     if not os.getenv('DISPLAY'):
  694.         mode = INTERACTIVE_MODE
  695.     elif not utils.checkPyQtImport():
  696.         mode = INTERACTIVE_MODE
  697.  
  698. if mode in (INTERACTIVE_MODE, NON_INTERACTIVE_MODE):
  699.     if device_uri and printer_name:
  700.         log.error("You may not specify both a printer (-p) and a device (-d).")
  701.         usage()
  702.  
  703.  
  704.     if printer_name:
  705.         printer_list = cups.getPrinters()
  706.         found = False
  707.         for p in printer_list:
  708.             if p.name == printer_name:
  709.                 found = True
  710.  
  711.         if not found:
  712.             log.error("Unknown printer name: %s" % printer_name)
  713.             sys.exit(1)
  714.  
  715.  
  716.     if not device_uri and not printer_name:
  717.         try:
  718.             device_uri = device.getInteractiveDeviceURI(bus, 'pcard')
  719.             if device_uri is None:
  720.                 sys.exit(1)
  721.         except Error:
  722.             log.error("Error occured during interactive mode. Exiting.")
  723.             sys.exit(1)
  724.  
  725.     try:
  726.         pc = photocard.PhotoCard( None, device_uri, printer_name )
  727.     except Error, e:
  728.         log.error("Unable to start photocard session: %s" % e.msg)
  729.         sys.exit(1)
  730.  
  731.     pc.set_callback(update_spinner)
  732.  
  733.     if pc.device.device_uri is None and printer_name:
  734.         log.error("Printer '%s' not found." % printer_name)
  735.         sys.exit(1)
  736.  
  737.     if pc.device.device_uri is None and device_uri:
  738.         log.error("Malformed/invalid device-uri: %s" % device_uri)
  739.         sys.exit(1)
  740.         
  741.     user_cfg.last_used.device_uri = pc.device.device_uri
  742.  
  743.     pc.device.sendEvent(EVENT_START_PCARD_JOB)
  744.  
  745.     try:
  746.         pc.mount()
  747.     except Error:
  748.         log.error("Unable to mount photo card on device. Check that device is powered on and photo card is correctly inserted.")
  749.         pc.umount()
  750.         pc.device.sendEvent(EVENT_PCARD_UNABLE_TO_MOUNT, typ='error')
  751.         sys.exit(1)
  752.  
  753.     log.info(utils.bold("\nPhotocard on device %s mounted" % pc.device.device_uri))
  754.     log.info(utils.bold("DO NOT REMOVE PHOTO CARD UNTIL YOU EXIT THIS PROGRAM"))
  755.  
  756.     output_dir = os.path.realpath(os.path.normpath(os.path.expanduser(output_dir)))
  757.  
  758.     try:
  759.         os.chdir(output_dir)
  760.     except OSError:
  761.         print utils.bold("ERROR: Output directory %s not found." % output_dir)
  762.         sys.exit(1)
  763.  
  764.  
  765.  
  766.     if mode == INTERACTIVE_MODE: # INTERACTIVE_MODE
  767.  
  768.         console = Console(pc)
  769.         try:
  770.             try:
  771.                 console . cmdloop()
  772.             except KeyboardInterrupt:
  773.                 log.error("Aborted.")
  774.             except Exception, e:
  775.                 log.error("An error occured: %s" % e)
  776.         finally:
  777.             pc.umount()
  778.  
  779.         pc.device.sendEvent(EVENT_END_PCARD_JOB)
  780.  
  781.  
  782.     else: # NON_INTERACTIVE_MODE
  783.         print "Output directory is %s" % os.getcwd()
  784.         try:
  785.             try:
  786.                 unload_list = pc.get_unload_list()
  787.                 print
  788.  
  789.                 if len(unload_list) > 0:
  790.  
  791.                     max_len = 0
  792.                     for u in unload_list:
  793.                         max_len = max(max_len, len(u[0]))
  794.  
  795.                     formatter = utils.TextFormatter(
  796.                             (
  797.                                 {'width': max_len+2, 'margin' : 2},
  798.                                 {'width': 12, 'margin' : 2, 'alignment' : utils.TextFormatter.RIGHT},
  799.                                 {'width': 12, 'margin' : 2},
  800.                             )
  801.                         )
  802.  
  803.                     print
  804.                     print utils.bold(formatter.compose(("Name", "Size", "Type")))
  805.  
  806.                     total = 0
  807.                     for u in unload_list:
  808.                          print formatter.compose(('%s' % u[0], utils.format_bytes(u[1]), '%s/%s' % (u[2], u[3])))
  809.                          total += u[1]
  810.  
  811.  
  812.                     print utils.bold("Found %d files to unload, %s\n" % (len(unload_list), utils.format_bytes(total, True)))
  813.                     print utils.bold("Unloading files...\n")
  814.                     total, delta, was_cancelled = pc.unload(unload_list, status_callback, None, True)
  815.                     print utils.bold("\n%s unloaded in %d sec (%d KB/sec)" % (utils.format_bytes(total), delta, (total/1024)/delta))
  816.  
  817.             except KeyboardInterrupt:
  818.                 log.error("Aborted.")
  819.                 pass
  820.  
  821.         finally:
  822.             pc.umount()
  823.  
  824.  
  825. else: # GUI_MODE
  826.  
  827.     from qt import *
  828.     from ui import unloadform
  829.  
  830.     a = QApplication(sys.argv)
  831.     QObject.connect(a,SIGNAL("lastWindowClosed()"),a,SLOT("quit()"))
  832.  
  833.     try:
  834.         w = unloadform.UnloadForm(bus, device_uri, printer_name)
  835.     except Error:
  836.         log.error("Unable to connect to HPLIP I/O. Please (re)start HPLIP and try again.")
  837.         sys.exit(1)
  838.  
  839.     a.setMainWidget(w)
  840.     w.show()
  841.  
  842.     a.exec_loop()
  843.  
  844. log.info("Done.")
  845. sys.exit(0)
  846.  
  847.